<template>
  <div class="appDetail">
    <div class="page-head">
      <div class="page-bread">
        <div class="bread-prev" @click="back">应用管理</div>
        <div class="bread-divider">/</div>
        <div class="bread-now">应用详情</div>
      </div>
      <div class="page-tool">
        <div class="tool-btn" @click="open('add')">新 增</div>
      </div>
    </div>
    <div class="page-body">
      <div class="detail-box">
        <div class="detail-pic">
          <img :src="applicationData.icon" alt="" />
        </div>
        <div class="detail-con">
          <div class="detail-tit">
            {{ applicationData.name }}
          </div>
          <div class="detail-row">
            <div class="key">上传人</div>
            <div class="val">
              {{ applicationData.user_name }}
            </div>
          </div>
          <div class="detail-row">
            <div class="key">备注</div>
            <div class="val">
              {{ applicationData.remark }}
            </div>
          </div>
        </div>
      </div>
      <div class="table_data">
        <el-scrollbar class="scroll-bar" >
          <el-table :data="tableData" stripe row-key="alarm_id" :fit="true">
            <el-table-column
              width="20"
            />
            <el-table-column prop="model_name" label="适配机型" width="300">
            </el-table-column>
            <el-table-column prop="system" label="系统" width="240">
              <template slot-scope="{ row }">
                <div>
                  {{ systems.find((o) => o.key == row.system).value }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="version"
              label="版本号"
              width="200"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              prop="author"
              width="200"
              label="作者"
              show-overflow-tooltip
            >
            </el-table-column>

            <el-table-column label="备注" prop="remark" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="status" label="当前状态" width="220">
              <template slot-scope="{ row }">
                <div>
                  {{ appStatuses.find((o) => o.key == row.status).value }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center">
              <template slot-scope="{ row }">
                <div class="operation-col">
                  <div
                    class="txt-btn ope-btn primary"
                    v-if="[1].includes(row.status)"
                    @click="groundStaus(row)"
                  >
                    待上架
                  </div>
                  <div
                    class="txt-btn ope-btn primary"
                    :class="{ hideButton: [2, 4].includes(row.status) }"
                    v-else
                    @click="checkStaus(row)"
                  >
                    {{
                      appStatusesReserve.find((o) => o.key == row.status).value
                    }}
                  </div>
                  
                  <div class="txt-btn primary" @click="appDelete(row)">
                    删除
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>
      </div>
      <div class="page-footer">
        <pagina-tion
          class="page-pager"
          v-show="total >= 0"
          :background="true"
          :total="total"
          :offset.sync="offset"
          :limit.sync="limit"
          @pagination="getChangePage"
        />
        <button class="page-button">确定</button>
      </div>
    </div>
    <!-- 新增和修改弹框 -->
    <el-dialog
      :visible.sync="model.visible"
      width="450px"
      :title="model.type === 'add' ? '新增版本' : '修改版本'"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="dialog-body">
        <el-form
          ref="form"
          :model="form"
          label-width="100px"
          label-position="left"
        >
          <el-form-item label="应用包" class="upload-form-item required">
            <el-tooltip
              v-if="fileName"
              effect="dark"
              placement="bottom"
              :content="fileName"
            >
              <el-input
                v-validate="'required'"
                :readonly="true"
                placeholder="请选择要上传的文件"
                v-model="fileName"
                name="appDetailFileName"
              />
            </el-tooltip>

            <el-input
              v-else
              v-validate="'required'"
              :readonly="true"
              placeholder="请选择要上传的文件"
              v-model="fileName"
              name="appDetailFileName"
            />
            
            <input
              type="file"
              accept="application/zip, application/vnd.android.package-archive, application/octet-stream, .msi, .exe"
              class="file-input"
              ref="fileInput"
              @change="fileChange($event)"
            />
            <img src="~assets/img/pick.png" class="pick-img" />
            <div
              v-show="errors.has('appDetailFileName')"
              class="el-form-item__error"
            >
              {{ errors.first("appDetailFileName") }}
            </div>
          </el-form-item>
          <el-form-item label="适配机型" class="required">
            <el-select
              class="appdetail-select"
              v-model="form.model_id"
              name="modelName"
              placeholder="请选择适配机型"
              v-validate="'required'"
            >
              <el-option
                v-for="item in modelSel"
                :key="item.model_id"
                :label="item.name"
                :value="item.model_id"
              />
            </el-select>
            <div v-show="errors.has('modelName')" class="el-form-item__error">
              {{ errors.first("modelName") }}
            </div>
          </el-form-item>
          <el-form-item label="系统" class="required">
            <el-select
              class="appdetail-select"
              v-model="form.system"
              name="system"
              placeholder="请选择系统"
              v-validate="'required'"
            >
              <el-option
                v-for="item in systems"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              />
            </el-select>
            <div v-show="errors.has('system')" class="el-form-item__error">
              {{ errors.first("system") }}
            </div>
          </el-form-item>
          <el-form-item label="版本号" class="required">
            <el-input
              v-model="form.version"
              name="version"
              v-validate="'required|maxLength16'"
            />
            <div v-show="errors.has('version')" class="el-form-item__error">
              {{ errors.first("version") }}
            </div>
          </el-form-item>
          <el-form-item label="作者" class="required">
            <el-input
              v-model="form.author"
              name="author"
              v-validate="'required|maxLength16'"
            />
            <div v-show="errors.has('author')" class="el-form-item__error">
              {{ errors.first("author") }}
            </div>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model.trim="form.remark" type="textarea" maxlength="128" />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="close()">取 消</el-button>
        <el-button type="primary" @click="submit(model.type)">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="stopVisable"
      width="450px"
      title="终止 License"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="dialog-body">
        <el-form
          ref="form"
          :model="form"
          label-width="90px"
          label-position="left"
        >
          <el-form-item label="终止原因">
            <el-input type="textarea" placeholder="请输入终止原因" />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="stopVisable = false">取消</el-button>
        <el-button type="primary" @click="submit(model.type)"
          >终止续约</el-button
        >
      </span>
    </el-dialog>

    <!-- 待审核弹窗 -->
    <el-dialog
      :visible.sync="visibilityResult"
      width="430px"
      height="100px"
      :show-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-content comfirm-body">
        <img class="comfirm-ico" src="~assets/img/warning.png" />
        <div class="comfirm-txt">
          <div>
            请选择审核结果
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="noPass">不通过</el-button>
        <el-button type="primary" @click="yesPass">通过</el-button>
      </span>
    </el-dialog>

    <!-- 待上架弹窗 -->
    <el-dialog
      :visible.sync="visibilityGroundResult"
      width="430px"
      height="100px"
      :show-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-content comfirm-body">
        <img class="comfirm-ico" src="~assets/img/warning.png" />
        <div class="comfirm-txt">
          <div v-if="typeAction === '上架'" key="up">请校验应用包是否合格？合格再上架</div>
          <div v-else key="other">请确定是否{{ typeAction }}</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancle">取 消</el-button>
        <el-button type="primary" @click="groundsubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 删除弹窗 -->
    <el-dialog
      :visible.sync="visibilityDelete"
      width="430px"
      height="100px"
      :show-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-content comfirm-body">
        <img class="comfirm-ico" src="~assets/img/warning.png" />
        <div class="comfirm-txt">
          <div>该数据确定要删除吗？</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="deletecancle">取 消</el-button>
        <el-button type="primary" @click="deleteSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Loading } from "element-ui";
import { limit, miniLimit } from "@/consts/consts";
import * as api from "@/api";
import { systems, appStatuses, appStatusesReserve } from "@/consts/codesMap";
import { apppDetailFormKey } from "@/consts/formKey";
import { md5 } from "@/utils/md5";
import client from "@/utils/oss";

export default {
  data() {
    return {
      limit: document.body.clientHeight>= 770 ? limit : miniLimit,
      total: 0,
      offset: 0,
      tableData: [],
      model: {
        type: "add",
        visible: false,
      },
      stopVisable: false,
      form: {
        name: "",
        roles: {},
      },
      applicationData: JSON.parse(sessionStorage.getItem("application")),
      fileName: "",
      modelSel: [],
      appStatuses,
      appStatusesReserve,
      systems,
      form: {
        ...apppDetailFormKey,
      },
      app_id: "",
      statusFrom: {},
      isShow: true,
      visibilityResult: false,
      typeAction: "",
      typeActionFotter: "",
      visibilityGroundResult: false,
      app_version_id: "",
      visibilityDelete: false,
      fileSize: "",
      loading: null,
    };
  },
  methods: {
    back() {
      this.$router.go(-1);
    },
    close() {
      this.model.visible = false;
      this.fileName = "";
      this.form = { ...apppDetailFormKey };
    },
    open(type, row = null) {
      this.$validator.reset();
      this.model.type = type;
      if (row) {
        for (const k in orgFormKey) {
          this.form[k] = row[k];
        }
        this.org_id = row.org_id;
      }
      this.model.visible = true;
    },

    getChangePage(val) {
      this.offset = val.offset;
      this.appVersionList();
    },
    submit(type) {
      this.$validator.validateAll().then((valid) => {
        if (valid) {
          this.addOrEdit();
        } else {
          this.$message.warning("有信息未填写正确");
        }
      });
    },
    fileChange(e) {
      let file = this.$refs.fileInput.files[0];
      let index = file.name.lastIndexOf(".")
      let suf = file.name.substr(index+1)
      const typeOk = ['zip', 'ZIP', 'apk', 'exe', 'msi'].includes(suf)
      if (typeOk) {
        this.fileSize = file.size;
        this.loading = Loading.service({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        md5(file).then((res) => {
          this.fileName = file.name;
          this.form.md5 = res;
          this.upload(file);
        });
        e.target.value = null;
      } else {
        this.$message.warning('只能上传zip、apk、exe、msi格式的文件')
      }
      
    },
    checkStaus(row) {
      //0-待审核 1-审核通过 2-审核失败 3-上架 4-下架
      if (row.status === 0) {
        // 待审核的接口
        this.typeAction = "待审核";
        this.typeActionFotter = "审核";
        this.statusFrom.app_version_id = row.app_version_id;
        this.visibilityResult = true;
      }
      if (row.status === 3) {
        this.typeAction = "下架";
        this.statusFrom.app_version_id = row.app_version_id;
        this.visibilityGroundResult = true;
      }
    },
    groundStaus(row) {
      this.typeAction = "上架";

      this.statusFrom.app_version_id = row.app_version_id;
      this.visibilityGroundResult = true;
    },

    yesPass() {
      if (this.typeAction === "待审核") {
        this.statusFrom.status = 1;
        this.appVersionExamine();
      }
    },
    noPass() {
      if (this.typeAction === "待审核") {
        this.statusFrom.status = 2;
        this.appVersionExamine();
      }
    },
    cancle() {
      this.visibilityGroundResult = false;
      this.appVersionExamine();
    },
    groundsubmit() {
      if (this.typeAction == "待上架") {
        this.statusFrom.status = 3;
        this.appVersionExamine();
      }
      if (this.typeAction == "上架") {
        this.statusFrom.status = 3;
        this.appVersionExamine();
      }
      if (this.typeAction == "下架") {
        this.statusFrom.status = 4;
        this.appVersionExamine();
      }
    },
    appDelete(row) {
      this.app_version_id = row.app_version_id;
      this.visibilityDelete = true;
    },
    deletecancle() {
      this.visibilityDelete = false;
    },
    deleteSubmit() {
      this.appVersiondDelete();
    },
    async addOrEdit() {
      let fn = this.model.type === "add" ? "appUpload" : "";
      this.app_id = this.$route.params.id;
      let sizeM = this.fileSize / 1024 / 1024;
      this.form.size = Math.ceil(sizeM) + "";
      const { code } = await api.application(this)[fn](this.form, this.app_id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.close();
        this.appVersionList();
      }
    },
    async appVersionList() {
      let obj = {};
      obj.offset = this.offset;
      obj.limit = this.limit;
      const { code, data, total } = await api
        .application(this)
        .appVersionList(obj, this.$route.params.id);
      if (code === 0) {
        this.tableData = data;
        this.total = total;
      }
    },
    async modelList() {
      const { code, data } = await api.dropdown(this).modelList();
      if (code === 0) {
        this.modelSel = data;
      }
    },
    async upload(file) {
      let arr = file.name.split(".")
      let [suf, ...rest] = [...arr].reverse()
      let n = rest.reverse().join('.')
      
      let fileName = `${n}_${+new Date()}.${suf}`;
      let result = await client.multipartUpload(`app/${fileName}`, file);

      if (result) {
        [this.form.url] = result.res.requestUrls[0].split("?");
        this.fileName = file.name;
        this.loading.close();
      }
    },
    // 审核的接口
    async appVersionExamine() {
      const { code, data } = await api
        .application(this)
        .appVersionExamine(this.statusFrom);
      if (code === 0) {
        this.visibilityResult = false;
        this.visibilityGroundResult = false;
        this.appVersionList();
      }
    },
    async appVersiondDelete() {
      const { data, code } = await api
        .application(this)
        .appVersiondDelete(this.app_version_id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.visibilityDelete = false;
        this.appVersionList();
      }
    },
  },
  created() {
    this.appVersionList();
    this.modelList();
  },
};
</script>

<style lang="stylus">
.appDetail {
  .detail-box {
    height: getPx(160);
    background: $bg-white;
    margin: getPx(10) auto getPx(30);
    flexMiddle(flex-start);

    .detail-pic {
      width: getPx(110);
      height: getPx(110);
      margin: 0 getPx(80);

      img {
        width: 100%;
        height: 100%;
      }
    }

    .detail-con {
      .detail-tit {
        color: $txt-color;
        font-size: $sub-font-size;
        font-weight: bold;
        margin: getPx(10) 0;
      }

      .detail-row {
        height: getPx(20);
        color: $mute-color;
        font-size: $sm-font-size;
        flexMiddle(flex-start);

        .key {
          width: getPx(60);
          flex: 1 getPx(60) 0%;
        }

        .val {
          flex: 3;
        }
      }
    }
  }
  .el-table__body{
    width:auto !important;
    }
  .table_data .el-scrollbar__view .el-table .el-table__header-wrapper .el-table__header {
    width: auto !important;
  }

 
}
</style>